package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    public PageResult findListById(String movementId, Integer page, Integer pagesize) {
        int count = commentApi.count(movementId, CommentType.COMMENT);
        //根据动态id分页查询评论列表
        List<Comment> commentList = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult();
        }
        //获取评论的人的id集合
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, count, vos);
    }
}
